﻿using Autofac;
using CrawlerApp.Configuration;
using CrawlerApp.Views;
using CrawlerApp.Infrastructure.Data;
using System.Reflection;
using System.Windows;
using CrawlerApp.Services.Interfaces.Job;
using CrawlerApp.Core.Entities.BookAggregate;
using Autofac.Extras.DynamicProxy;
using CrawlerApp.Infrastructure.Interfaces;
using System;
using CrawlerApp.Infrastructure.Services;
using System.Threading.Tasks;
using StackExchange.Profiling.Internal;

namespace CrawlerApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        internal IContainer Container;

        public App()
        {
            ContainerBuilder builder = new ContainerBuilder();
            this.AddInfraService(builder);
            this.AddCoreServices(builder);
            this.AddAppServices(builder);
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());                
            Container = builder.Build();            
        }

        private void Start(object sender, StartupEventArgs e)
        {
            Container.Resolve<DiagnosticInitializer>()?.Start();

            // 初始化数据库
            Container.Resolve<ApplicationDbContext>().Database.EnsureCreated();

            // 开始任务调度
            //Container.Resolve<IJobService>().Start();

            var repository = Container.Resolve<IBookRepository>();
            var book = new Book($"name{new Random().Next()}", $"href{new Random().Next()}");

            Task.FromResult(repository.AddAsync(book));

            Container.Resolve<MainWindow>().Show();
        }

        private void AppExit(object sender, ExitEventArgs e)
        {
            Container.Resolve<IJobService>().Shutdown();
        }
    }
}
